package socket

import (
	"net"
	"encoding/json"
	"net/http"

	"log"
	"github.com/gorilla/websocket"
	"gitee.com/DengAnbang/Computation/src/bean"
	"gitee.com/DengAnbang/goutils/loge"
	"errors"
	"fmt"
)

func WebSocketRun(w http.ResponseWriter, r *http.Request) {
	upgrader := websocket.Upgrader{
		// 解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	webSocketHandler(c)
}
func webSocketHandler(ws *websocket.Conn) {
	defer ws.Close()
	conn := WsConn{Conn: ws}
	conn.SendMessageToConn(bean.NewSucceedMessage("连接成功!"))
	for {
		if _, message, err := ws.ReadMessage(); err != nil {
			loge.WD("receive failed:", err.Error())
			if _, ok := err.(*websocket.CloseError); ok {
				UnRegister(&conn)
				return
			}
			break
		} else {
			var sm bean.RequestData
			err := json.Unmarshal(message, &sm)
			loge.WD("读取到的消息:" + string(message))
			if err == nil {
				go Dispense(&sm, &conn)
			} else {
				conn.Response(errors.New(fmt.Sprintf("编码错误,%s", message)), 0)
			}
		}

	}
}

func TcpRun(port string) {
	netListen, err := net.Listen("tcp", ":"+port)
	if err != nil {
		loge.W(err)
		panic(err)
	}
	defer netListen.Close()
	for {
		conn, err := netListen.Accept()
		if err != nil {
			loge.W(err)
			continue
		}
		loge.WD("连接成功请求地址:" + conn.RemoteAddr().String())
		go tcpSocketHandler(conn)
	}
}
func tcpSocketHandler(conn net.Conn) {
	tcpConn := TcpConn{headerLength: HeaderLength, Conn: conn}
	err := tcpConn.SendMessageToConn(bean.NewSucceedMessage("连接成功!"))
	if err != nil {
		loge.W(err)
	}
	data := make(chan []byte)
	go tcpConn.ReadConn(data)
	for {
		select {
		case v, ok := <-data:
			if ok {
				var sm bean.RequestData
				err := json.Unmarshal(v, &sm)
				loge.WD("读取到的消息:" + string(v))
				if err == nil {
					go Dispense(&sm, &tcpConn)
				} else {
					tcpConn.Response(errors.New(fmt.Sprintf("编码错误:%s", string(v))), 0)
				}
			} else {
				UnRegister(&tcpConn)
				loge.WD("关闭:" + tcpConn.Id)
				return
			}
		}
	}

}
